package com.hynet.customer;

import com.aliyun.tea.TeaException;
import com.google.gson.Gson;
import com.hynet.customer.client.Client;
import com.hynet.customer.client.models.*;
import org.junit.jupiter.api.Test;

import java.text.SimpleDateFormat;
import java.util.Date;



/**
 *  注意 Application 使用的是sm2的方法，使用rsa2密钥的请看ApplicationRsa2
 *
* 汇付宝客户中心demo
*
* 开发环境 jdk1.8
*
* 如有demo技术问题对接群里@技术支持
*
* 接口开发API文档： https://open.heepay.com/www/index.html#/openDoc?type=menu&id=2022  ------>  寻找客户中心一栏
*
* 入驻申请+入驻修改+入驻结果查询+文件上传+行政区划查询
*
* 1.先调文件上传获取入驻需要文件的路径
* 2.然后根据自己系统逻辑开发行政区划查询
* 3.调入驻同步返回入驻编号则为开户成功
* 4.如果需要修改信息调修改接口即可
* 5.同步返回不需要验签,但是异步的入驻通知需要验签,验签规则和签名同理,也可以调用   com.hynet.customer.client.common.HynetUtil.verify方法
* 6.签名规则
签名通用步骤第一步，设所有发送或者接收到的数据为集合M，将集合M内非空参数值的参数按照参数名ASCII码从小到大排序（字典序），使用URL键值对的格式（即key1=value1&key2=value2…）拼接成字符串stringA 特别注意以下重要规则：
参数名ASCII码从小到大排序（字典序）；
如果参数的值为空不参与签名；
参数名区分大小写；第二步，使用商户SM2私钥对待签名字符串stringA进行签名，得到签名sign
验签用到的是汇付宝公钥验签
*/


public class Application {


    private static Config getConfig() {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Config config = new Config();
        config.setProtocol("https");
        config.setMethod("POST");
        config.setPathname("/customer-api/gateway");
        config.setHost("openapi.heepay.com");
        /*
        第一步， 商户自行生成国密SM2密钥对（公钥、私钥）,并将公钥通过邮件发送给我方(yunyingbu@9186.com)
               邮件标题：汇元网客户中心平台-商户-发送商户公钥
               邮件内容：商户SM2公钥+商户公司名称+商户号
        第二步，汇元网回复客户中心平台公钥给该商户
               邮件标题：汇元网客户中心平台-商户-回复平台公钥
               邮件内容：汇元平台SM2公钥+商户APPID

               密钥用支付宝小程序的密钥生成工具去生成

        注意：建议先用测试账号联调，之后正式账号下来再使用,测试账号联调的时候,联系人邮箱不要传真实的,  如果账户号没下来，请在对接群@运营，会有人回复

         目前使用的hykj-sm2002为测试账号
        */
        config.setApp_id("hykj-sm2001");
        config.setFormat("json");
        config.setCharset("utf-8");
        config.setSign_type("SM2");
        config.setTimestamp(simpleDateFormat.format(new Date()));
        config.setVersion("1.0");
        //商户私钥
        config.setMchPrivateKey("MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgDpZH4qGFl8DjrusKbCW4jEEKsH0ilWdCjapJSRmRWqugCgYIKoEcz1UBgi2hRANCAATZAX2SXFj2i0S3IEfkGLvDo/zq6Jt4cDz3+EJVm7jP2e8lw6YM2bYIQc4GpRtNC5Km49eOb+PULWMWnrrD1lu6");
        //该公钥为测试账号汇元公钥
        config.setHyPublicKey("MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEK2X3eSO4M3CSzlJfajjtlpqayQ0DQ0UfSLiAa6APukvaq3OgDnDYOfx5TeNUUGWGCKHJhBRZcB7Nccl/XCr55w==");



        return config;
    }




    public static void main(String[] args) {
        //入驻企业申请
        //customerEntryApply1();
        //入驻个体申请
        //customerEntryApply2();
        //入驻小微申请
        //customerEntryApply3();
        //入驻修改
        //customerEntryModify();
        //入驻结果查询
        //customerEntryQuery();
        //结算银行卡信息查询
        //customerSettleCards();
        //商户信息查询
        //customerInfo();
        //上游进件结果查询（微信、支付宝等）
        //customerChannelEntryQuery();
        //查询微信开户意愿审核结果
        //customerWxQuery();
        //查询支付宝开户意愿审核结果
        //customerAliPayQuery();
        //查询授权目录
        //customerAuthCatalogGet();
    }


    /*
    * 行政区划查询
    * 根据行政区划代码（省份或城市）编码 行政区划类型=1时，可传空值。城市用省份的region_code字段查询，区县用城市的region_code字段查询
    * @param region_code 行政区划代码
    * @param region_type 行政区划类型 1=省份 2=城市 3=区县
    */
    @Test
    public void queryRegionCodeTest() {
        try {
            // 行政区划代码查询
            RegionRequest request = new RegionRequest();
            request.setRegion_code("429000");
            request.setRegion_type(3);
            sendRequest("customer.region.query", request);
        } catch (Exception e) {
            System.out.println("查询行政区划代码时发生错误：" + e.getMessage());
        }
    }


    /*
    * 文件上传
    * 上传文件到服务器，返回上传成功后的文件路径
    * @param credentialType 文件类型
    * @param filePath 文件路径
    */
    @Test
    public void fileUploadTest() {
        upload("customer.media.upload", "02", "D:\\picture\\5.png");
    }







    /**
    企业入驻请求参数
    customer_type=1
    */

    private static void customerEntryApply1() {
        CustomerEntryApplyRequest request = new CustomerEntryApplyRequest();
        request.setIf_sign(1);
        //客户类型
        request.setCustomer_type(1);

        /*
        register_type为账户类型（默认收单）
        非必传：默认为收单商户，HEEPAY_MERCH=收单商户；HEEPAY_BALANCE=钱包账户
        request.setregister_type("HEEPAY_MERCH");
        */

        request.setCustomer_name("小二小黑科技有限公司");
        request.setCustomer_short_name("小二黑");
        request.setCustomer_phone("16666666666");

        /*
        licence为营业执照信息
         */
        request.setLicence_address("北京市海淀区中关村");
        //营业执照区划编码 精确到区 北京市-北京市-海淀区 = 110108
        //request.setlicence_region_code("110108");
        request.setLicence_province_code("28");
        request.setLicence_city_code("851");
        request.setLicence_are_code("-1");

        request.setLicence_valid_begin("2021-04-01");
        //营业执照失效日期（yyyy-MM-dd）有效期为定期必传
        request.setLicence_valid_end("2031-04-01");
        //营业执照有效期类型  1=定期,2=长期
        request.setLicence_valid_type(1);
        request.setLicence_code("98765112MA7HB5C89Q");
        //经营类目编码，参见附录
        request.setBusiness_category_code("1000");

        /*
        legal法人信息
        */
        request.setLegal_name("王大锤");
        request.setLegal_id_card("411000200006010033");
        request.setLegal_id_card_valid_begin("2023-10-26");
        request.setLegal_id_card_valid_end("");
        request.setLegal_id_card_valid_type(2);
        request.setLegal_mobile("16666666666");

        /*
        contact联系人信息（联系人可以和法人同名）
        */
        request.setContact_name("王大锤");
        request.setContact_id_card("411000200006010033");
        request.setContact_id_card_valid_begin("2022-10-26");
        request.setContact_id_card_valid_end("2032-10-26");
        request.setContact_id_card_valid_type(1);
        request.setContact_mobile("16666666661");
        //只能用一次不能重复
        request.setContact_email("1666666666111141@qq.com");

        /*
        Bank结算银行卡信息
        */
        request.setBank_account_name("小二小黑科技有限公司");
        //结算银行账户类型  1=对公 企业只能对公
        request.setBank_account_type(1);
        request.setBank_card_no("6227002007566666666");
        request.setBank_name("建设银行");

        //结算银行所属区划编码精确到市就可以   北京市-北京市 = 110100
        request.setbank_region_code("110100");

        //提现类型，不传默认1  1=手动提现,2=自动提现 大户可以通过接口代子户提现，接口文档对接群里要
        request.setWithdraw_type(1);

        request.setbeneficiary_is_legal("1");
        //注意格式
        //request.setbeneficiary_infos("[{\"address\":\"北京山顶洞\",\"birthday\":\"2022-12-25\",\"cert_no\":\"111111111111111111\",\"cert_type\":1,\"cert_valid_date\":\"2032-12-31\",\"name\":\"王一\",\"national\":1,\"rate\":30},{\"address\":\"北京山顶洞\",\"birthday\":\"2022-12-25\",\"cert_no\":\"111111111111111112\",\"cert_type\":1,\"cert_valid_date\":\"2032-12-31\",\"name\":\"王二\",\"national\":1,\"rate\":30},{\"address\":\"北京山顶洞\",\"birthday\":\"2022-12-25\",\"cert_no\":\"111111111111111113\",\"cert_type\":1,\"cert_valid_date\":\"2032-12-31\",\"name\":\"王三\",\"national\":1,\"rate\":40}]");



        request.setCompany_build_img("17471912500340af480cf20945896322");
        request.setCompany_front_img("17471912500340af480cf20945896322");
        request.setShop_env_img("17471912500340af480cf20945896322");
        request.setLicence_img("17471912500340af480cf20945896322");
        request.setReg_certificate_img("17471912500340af480cf20945896322");
        request.setLegal_id_card_front_img("17471912500340af480cf20945896322");
        request.setLegal_id_card_back_img("17471912500340af480cf20945896322");
        request.setContact_id_card_front_img("17471912500340af480cf20945896322");
        request.setContact_id_card_back_img("17471912500340af480cf20945896322");

        sendRequest("customer.entry.apply", request);
    }


    /**
    个体户入驻请求参数
    customer_type=2
    */

    private static void customerEntryApply2() {
        CustomerEntryApplyRequest request = new CustomerEntryApplyRequest();
        request.setIf_sign(1);
        //客户类型
        request.setCustomer_type(2);
        /*
        register_type为账户类型（默认收单）
        非必传：默认为收单商户，HEEPAY_MERCH=收单商户；HEEPAY_BALANCE=钱包账户
        request.setregister_type("HEEPAY_MERCH");
        */
        request.setCustomer_name("小三黑科技有");
        request.setCustomer_short_name("小三黑");
        request.setCustomer_phone("16699999999");

        /*
        licence为营业执照信息
         */
        request.setLicence_address("湖南省长沙市芙蓉区");
        //营业执照区划编码 精确到区 北京市-北京市-海淀区 = 110108
        request.setlicence_region_code("110108");




        request.setLicence_valid_begin("2021-04-01");
        //营业执照失效日期（yyyy-MM-dd）有效期为定期必传
        request.setLicence_valid_end("2031-04-01");
        //营业执照有效期类型  1=定期,2=长期
        request.setLicence_valid_type(1);
        request.setLicence_code("98765113MA7HB5C29P");
        //经营类目编码，参见附录
        request.setBusiness_category_code("1124");

        /*
        manage经营者信息
        */
        request.setManage_name("王二锤");
        request.setManage_id_card("410622202310266012");
        request.setManage_id_card_valid_begin("2023-10-26");
        request.setManage_id_card_valid_end("");
        request.setManage_id_card_valid_type(2);
        request.setManage_mobile("16666667777");
        request.setmanage_region_code("110108");
        request.setManage_detail_address("北京市海淀区中关村");

        /*
        contact联系人信息
        */
        request.setContact_name("王二锤");
        request.setContact_id_card("410622202210266012");
        request.setContact_id_card_valid_begin("2022-10-26");
        request.setContact_id_card_valid_end("2032-10-26");
        request.setContact_id_card_valid_type(1);
        request.setContact_mobile("16666667771");
        //只能用一次不能重复
        request.setContact_email("161@qq.com");

        /*
        Bank结算银行卡信息
        */
        request.setBank_account_name("小三黑科技有");
        //结算银行账户类型  1=对公 2=对私
        request.setBank_account_type(1);
        request.setBank_card_no("6227002007566666661");
        request.setBank_name("建设银行");

        //结算银行所属区划编码精确到市就可以   北京市-北京市 = 110100
        request.setbank_region_code("110100");

        //提现类型，不传默认1  1=手动提现,2=自动提现 大户可以通过接口代子户提现，接口文档对接群里要
        request.setWithdraw_type(2);

        //受益人是否是法人，收单户必填，钱包户选填 默认0，如果是1，法人的控股比例是100%
        request.setbeneficiary_is_legal("0");
        //注意格式
        request.setbeneficiary_infos("[{\"address\":\"北京山顶洞\",\"birthday\":\"2022-12-25\",\"cert_no\":\"111111111111111111\",\"cert_type\":1,\"cert_valid_date\":\"2032-12-31\",\"name\":\"王一\",\"national\":1,\"rate\":30},{\"address\":\"北京山顶洞\",\"birthday\":\"2022-12-25\",\"cert_no\":\"111111111111111112\",\"cert_type\":1,\"cert_valid_date\":\"2032-12-31\",\"name\":\"王二\",\"national\":1,\"rate\":30},{\"address\":\"北京山顶洞\",\"birthday\":\"2022-12-25\",\"cert_no\":\"111111111111111113\",\"cert_type\":1,\"cert_valid_date\":\"2032-12-31\",\"name\":\"王三\",\"national\":1,\"rate\":40}]");



        request.setCompany_build_img("17471912500340af480cf20945896322");
        request.setCompany_front_img("17471912500340af480cf20945896322");
        request.setShop_env_img("17471912500340af480cf20945896322");
        request.setShop_cashier_img("17471912500340af480cf20945896322");
        request.setShop_front_img("17471912500340af480cf20945896322");
        request.setLicence_img("17471912500340af480cf20945896322");
        request.setReg_certificate_img("17471912500340af480cf20945896322");
        request.setManage_id_card_front_img("17471912500340af480cf20945896322");
        request.setManage_id_card_back_img("17471912500340af480cf20945896322");
        request.setManage_hold_id_card_front_img("17471912500340af480cf20945896322");
        request.setManage_hold_bank_front_img("17471912500340af480cf20945896322");
        request.setContact_id_card_front_img("17471912500340af480cf20945896322");
        request.setContact_id_card_back_img("17471912500340af480cf20945896322");


        sendRequest("customer.entry.apply", request);
    }


      /**
      小微入驻请求参数
      customer_type=3
      */
    private static void customerEntryApply3() {
        CustomerEntryApplyRequest request = new CustomerEntryApplyRequest();
        request.setIf_sign(1);
        //客户类型
        request.setCustomer_type(3);
        /*
        register_type为账户类型（默认收单）
        非必传：默认为收单商户，HEEPAY_MERCH=收单商户；HEEPAY_BALANCE=钱包账户
        request.setregister_type("HEEPAY_MERCH");
        */
        request.setCustomer_name("爱吃肉肉肉是我w11ww11");

        //经营类目编码，参见附录
        request.setBusiness_category_code("1000");

        /*
        manage经营者信息
        */
        request.setManage_name("爱吃肉肉肉是我w11ww11");
        request.setManage_id_card("111111199906060053");
        request.setManage_id_card_valid_begin("2023-10-26");
        request.setManage_id_card_valid_end("");
        request.setManage_id_card_valid_type(2);
        request.setManage_mobile("16666669966");
        request.setmanage_region_code("110108");
        request.setManage_detail_address("北京市海淀区中关村");

        /*
        contact联系人信息
        */
        //只能用一次不能重复
        request.setContact_email("78978978971118978197@qq.com");

        /*
        Bank结算银行卡信息
        */
        request.setBank_account_name("爱吃肉肉肉是我w11ww11");
        //小微 2=对私 只能对私
        request.setBank_account_type(2);
        request.setBank_card_no("6227002007566612399");
        request.setBank_name("建设银行");

        //结算银行所属区划编码精确到市就可以   北京市-北京市 = 110100
        request.setbank_region_code("110100");

        //提现类型，不传默认1  1=手动提现,2=自动提现 大户可以通过接口代子户提现，接口文档对接群里要
        request.setWithdraw_type(2);

        //费率信息，json格式，注意key为：支付场景，value为费率，费率目前只支持百分，千分，万分，支付场景详见文档底部附录：支付场景。（收单户必填，没有费率会导致订单无法结算
        request.setheepay_info("{\"rate\":{\"WX_JSAPI\":0.006,\"WX_QRCODE\":0.006,\"WX_MINI\":0.006}}");


        request.setCompany_build_img("17471912500340af480cf20945896322");
        request.setCompany_front_img("17471912500340af480cf20945896322");
        request.setShop_front_img("17471912500340af480cf20945896322");
        request.setShop_env_img("17471912500340af480cf20945896322");
        request.setShop_cashier_img("17471912500340af480cf20945896322");
        request.setBank_back_img("17471912500340af480cf20945896322");
        request.setBank_front_img("17471912500340af480cf20945896322");
        request.setBank_owner_hold_img("17471912500340af480cf20945896322");
        request.setLicence_img("17471912500340af480cf20945896322");
        request.setManage_id_card_front_img("17471912500340af480cf20945896322");
        request.setManage_id_card_back_img("17471912500340af480cf20945896322");
        request.setManage_hold_bank_front_img("17471912500340af480cf20945896322");
        request.setManage_hold_id_card_front_img("17471912500340af480cf20945896322");
        request.setSharing_protocol("17471912500340af480cf20945896322");

        sendRequest("customer.entry.apply", request);
    }





    /**
     * 入驻修改
     */

    private static void customerEntryModify() {
        CustomerEntryModifyRequest request = new CustomerEntryModifyRequest();

        request.setApply_no("210618142808005001");
        request.setRegister_type("HEEPAY_MERCH");
        sendRequest("customer.entry.modify", request);
    }



    /**
     * 入驻结果查询
     */

    private static void customerEntryQuery() {
        CustomerEntryQueryRequest request = new CustomerEntryQueryRequest();
        request.setApply_no("");
        request.setCustomer_id("240322142042034323");
        request.setEmail("");
        sendRequest("customer.entry.query", request);
    }


    /**
     * 结算银行卡信息查询
     */


    private static void customerSettleCards() {
        SettleCardsRequest request = new SettleCardsRequest();
        request.setCustomer_id("");
        request.setProduct_id(Integer.valueOf("1000"));
        sendRequest("settle.cards", request);
    }

    /**
     * 商户信息查询
     */

    private static void customerInfo() {
        CustomerInfoRequest request = new CustomerInfoRequest();
        request.setApply_no("");
        request.setCustomer_id("");
        request.setEmail("");
        sendRequest("customer.info", request);
    }


    /**
     * 上游进件结果查询（微信、支付宝等）
     */

    private static void customerChannelEntryQuery() {
        CustomerChannelEntryQueryRequest request = new CustomerChannelEntryQueryRequest();
        request.setCustomer_id("");
        request.setService_type("1000");
        sendRequest("customer.channel-entry.query", request);
    }


    /**
     * 查询微信开户意愿审核结果
     */

    private static void  customerWxQuery() {
        CustomerWxQueryRequest request = new CustomerWxQueryRequest();
        request.setCustomer_id("");
        request.setService_type("1000");
        sendRequest("customer.wx.query", request);
    }


    /**
     * 查询支付宝开户意愿审核结果
     */

    private static void  customerAliPayQuery() {
        CustomerAliPayQueryRequest request = new CustomerAliPayQueryRequest();
        request.setCustomer_id("10000");
        request.setService_type("1000");
        sendRequest("customer.alipay.query", request);
    }



    /**
     * 行政区划代码查询
     */

    private static void regionQuery() {
        RegionRequest request = new RegionRequest();
        request.setRegion_code("130000");
        request.setRegion_type(1);
        sendRequest("customer.region.query", request);
    }


    /**
     * 查询授权目录
     */

    private static void customerAuthCatalogGet() {
        AuthCatalogGetRequest request = new AuthCatalogGetRequest();
        request.setCustomer_id("210618142808005001");
        request.setAuth_channel(1);
        sendRequest("customer.auth.catalog.get", request);
    }


    private static void sendRequest(String method, Object request) {

        Gson json = new Gson();
        System.out.println("调用接口method：" + method);
        Config config = getConfig();
        config.setNotify_url("http://www.example.com/notify");
        System.out.println("构造的公共参数：" + config.toString());
        System.out.println("构造的业务参数：" + json.toJson(request));

        ApiResponse response = null;
        try {
            Client client = new Client(config);
            response = client.callApi(method, request);
            System.out.println("响应数据：" + json.toJson(response));
        } catch (TeaException e) {
            System.out.println("响应数据：code=" + e.getCode() + ",msg=" + e.getMessage());
        } catch (Exception ignored) {
        }

    }

    private static void upload(String method, String credentialType, String filePath) {

        Gson json = new Gson();
        System.out.println("调用接口method：" + method);
        Config config = getConfig();
        config.setPathname("/customer-api/customer.media.upload");
        System.out.println("构造的上传资料参数：" + config.toString());
        System.out.println("上传的图片路径：" + filePath);

        ApiResponse response = null;
        try {
            Client client = new Client(config);
            response = client.uploadApi(method, credentialType, filePath);
            System.out.println("响应数据：" + json.toJson(response));
        } catch (TeaException e) {
            System.out.println("响应数据：code=" + e.getCode() + ",msg=" + e.getMessage());
        } catch (Exception ignored) {
        }

    }


}
